<?php
namespace app\index\controller;

use app\common\controller\HomeBase;
use think\Db;
use app\common\model\User as UserModel;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Session;
use think\facade\Url;

class User extends HomeBase
{
    protected function initialize()
    {
        parent::initialize();
        $this->assign('page_type','');
        $this->checkLogin();

    }

    public function index()
    {
        $this->site_seo("home");
        return $this->fetch('index',['act' => 'index']);
    }

    public function login()
    {
        if ($this->request->isPost())
        {
            $phone = trim($this->request->param('phone'));
            $code = trim($this->request->param('code'));

            if (empty($phone) || empty($code) || strlen($code) == 0)
            {
                return $this->echoJson("",-1,"请填写手机号或者验证码!");
            }

            if (!check_mobile_number($phone)){
                return $this->echoJson("",-1,"填写的手机号码不正确!");
            }

            if (strlen($code) != 4){
                return $this->echoJson("",-1,"填写的手机验证码长度不正确!");
            }

            if (Cache::get("verify_code_" . md5($this->request->ip())) == $code)
            {
                if (!UserModel::checkUserIsExist("phone",$phone,'')) {
                    UserModel::createUser($phone,'',$phone, md5(rand(1000, 10000) . time()), 0, "phone",'');
                }
                UserModel::userLogin("phone",$phone,'');
                // 设置验证码为空
                Cache::set("verify_code_" . md5($this->request->ip()),"");
                return $this->echoJson("",200,"登录成功");
            }else {
                return $this->echoJson("",-1,"验证码不匹配");
            }
        }
    }

    /**
     * 个人信息设置
     * @return mixed
     */
    public function info()
    {
        if ($this->request->isPost())
        {
            $nickName = trim($this->request->param('nickname'));
            $realName = trim($this->request->param('realname'));
            $idcard = trim($this->request->param('idcard'));

            $res = model('user')->save([
                'nickname' => $nickName,
                'realname' => $realName,
                'idcard' => $idcard
            ],['id' => $this->user_info['id']]);

            if ($res)
            {
                return $this->success("保存成功");
            }else {
                return $this->error("保存失败");
            }

        }else {
            $this->site_seo("home");
            return $this->fetch('info',['act' => 'info']);
        }
    }

    /**
     * 微信绑定
     * @return mixed|void
     */
    public function bind()
    {
        if ($this->request->isPost())
        {
            return $this->success("保存成功");
        }else {
            $this->site_seo("home");
            return $this->fetch('bind',['act' => 'bind']);
        }
    }

    public function document()
    {
        $this->site_seo("home");
        return $this->fetch('bind',['act' => 'bind']);
    }

    /**
     * 订单列表
     * @return mixed
     */
    public function order()
    {
        $list = model('order')->where(['user_id' => $this->user_info['id']])->limit(10)->select()->each(function ($item){
            $title = model('vip')->where(['id' => $item['vip_id']])->column("title");
            if (empty($title)) {
                $item['title'] = "未知";
            }else{
                $item['title'] = $title[0];
            }
            return $item;
        });
        $this->site_seo("home");
        return $this->fetch('order',['act' => 'order','list' => $list]);
    }

    /**
     * 下载记录
     * @return mixed
     */
    public function download()
    {
        $list = model('down_log')->where(['user_id' =>  $this->user_info['id']])->limit(15)->order(['id' => 'desc'])->select();
        $this->site_seo("home");
        return $this->fetch('download',['act' => 'download','list' => $list]);
    }

    public function real()
    {
        $this->site_seo("home");
        return $this->fetch('bind',['act' => 'real']);
    }

    /**
     * 消息中心
     * @param int $page
     * @return mixed
     * @throws
     */
    public function message($page = 1)
    {
        $this->checkLogin();

        $list = model('message')->where('to','eq', $this->user_info['user_id'])->order('id DESC')->paginate(15, false, ['page' => $page]);

        foreach ($list as $key => $item) {
            $user = model('user')->where('id','eq',$item['from'])->field('nickname')->find();
            $pan = model('dupan')->where('id','eq',$item['pan_id'])->field('title')->find();

            $list[$key]['from_name'] = $user['nickname'];
            $list[$key]['pan_title'] = $pan['title'];
        }

        return $this->fetch('message',['list' => $list]);
    }


    /**
     * 退出
     * @return mixed
     */
    public function logout()
    {
        Session::set('user_info', "");
        $this->success("退出成功");
    }


    public function callback () {
        $type = $this->request->param("type");
        $code = $this->request->param("code");
        $state = $this->request->param("state");

        if ($type == "weixin") {
            $config = Config::pull("weixin");

            $data = curl_url(sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", $config['appid'],$config['secret'],$code));
            $data = json_decode($data['data'],true);
            if (array_key_exists("access_token",$data)) {
                $url = sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s",$data['access_token'],$data['openid']);
                $data = json_decode(curl_url($url)['data'],true);

                if (!UserModel::checkUserIsExist("weixin","",$data['openid'])) {
                    UserModel::createUser("", $data['headimgurl'], $data['nickname'], md5(rand(1000, 10000) . time()), $data['sex'], "weixin", $data['openid']);
                }
                UserModel::userLogin("weixin","",$data['openid']);
            }
        }

        return $this->redirect(Url::build("/","","",true));
    }


    /**
     * QQ互联回调页面
     */
//    public function qqCallback()
//    {
//        $oauth = new \qq_connect\Oauth();
//        $accesstoken = $oauth->qq_callback();
//        $openid = $oauth->get_openid();
//
//        $qc = new \qq_connect\QC($accesstoken, $openid);
//        $userinfo = $qc->get_user_info();
//
//        if (UserModel::checkUserIsExist('qq', '', strtolower($openid))) {
//
//            $info = UserModel::userLogin('qq', '', '', strtolower($openid));
//            if ($info['code'] == 200) {
//                $this->success("登陆成功", url('/forum', array(), 'html', true));
//            } else {
//                $this->error($info['msg']);
//            }
//
//        } else {
//            if ($userinfo['ret'] == 0) {
//                $gender = 0;
//                if ($userinfo['gender'] == '男') {
//                    $gender = 1;
//                } else if ($userinfo['gender'] == '女') {
//                    $gender = 2;
//                }
//
//                $res = UserModel::createUser('', $userinfo['figureurl_qq_2'], $userinfo['nickname'], rand(1000, 9999), $gender, 'qq', strtolower($openid));
//
//                if ($res > 1) {
//                    $info = UserModel::userLogin('qq', '', '', strtolower($openid));
//                    if ($info['code'] == 200) {
//                        $this->success("注册成功", url('/forum', array(), 'html', true));
//                    } else {
//                        $this->error($info['msg']);
//                    }
//                }
//
//            } else {
//                $this->error("授权信息异常!");
//            }
//        }
//
//    }
}
